package com.runchamp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;


public class HistoryRaces extends Fragment implements AdapterView.OnItemClickListener { // implements AdapterView.OnItemClickListener

    public String path = "http://runtobo.appspot.com/recordManager";
    private JSONAdapterHistoryRacesList mJSONAdapter;
    private long user;
    private Button timeButton, distanceButton, gradeButton, positionButton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final SharedPreferences prefs = getActivity().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
        user = Long.valueOf(prefs.getString("userID", ""));

        /**
         * Adding our layout to parent class frame layout.
         */
        View rootView = inflater.inflate(R.layout.activity_history_races, container, false);

        /**
         * Setting title and itemChecked
         */
        timeButton = (Button) rootView.findViewById(R.id.button_time);
        distanceButton = (Button) rootView.findViewById(R.id.button_distance);
        gradeButton = (Button) rootView.findViewById(R.id.button_grade);
        positionButton = (Button) rootView.findViewById(R.id.button_position);
        gradeButton.setTextColor(Color.argb(255, 67, 193, 228));

        timeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sortByTime(v);
            }
        });
        distanceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sortByDistance(v);
            }
        });
        gradeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sortByGrade(v);
            }
        });
        positionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sortByPosition(v);
            }
        });


        // Have the client get a JSONArray of data
        // and define how to respond
        AsyncHttpClient client = new AsyncHttpClient();

        ListView racesListView;
        mJSONAdapter = new JSONAdapterHistoryRacesList(getActivity(), inflater);
        racesListView = (ListView) rootView.findViewById(R.id.main_listview);
        racesListView.setAdapter(mJSONAdapter);
        racesListView.setOnItemClickListener(this);
        //racesListView.setOnItemClickListener(this); TODO open history race info with the finish table
        client.get(String.format("%s/myRaces?user=%s", path, user),
                new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(JSONArray jsonObject) {
                        mJSONAdapter.updateData(jsonObject);
                        mJSONAdapter.sortByGrade();
                    }

                    @Override
                    public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
                        String o = "o";
                    }
                });
        return rootView;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        JSONObject jsonObject = (JSONObject) mJSONAdapter.getItem(position);
        Intent raceHisoryIntent = new Intent(getActivity(), RaceHistoryInfoActivity.class);
        String isFinished = (jsonObject.optString("IsFinished").equals("true")) ? "Finished race" : "Not Finished";
        raceHisoryIntent.putExtra("Distance", String.format("%.2f", Float.parseFloat(jsonObject.optString("TotalDistance"))));
        raceHisoryIntent.putExtra("RaceDate", jsonObject.optString("Date"));
        raceHisoryIntent.putExtra("ActualTime", jsonObject.optString("Time"));
        raceHisoryIntent.putExtra("Grade", jsonObject.optString("Grade"));
        raceHisoryIntent.putExtra("ActualDistance", String.format("%.2f", Float.parseFloat(jsonObject.optString("Distance"))));
        raceHisoryIntent.putExtra("isFinished", isFinished);
        raceHisoryIntent.putExtra("position", jsonObject.optString("Position"));
        startActivity(raceHisoryIntent);
    }


    //////Sort functions///////

    public void sortByDistance(View view) {
        distanceButton.setTextColor(Color.argb(255, 67, 193, 228));
        timeButton.setTextColor(Color.argb(255, 255, 255, 255));
        positionButton.setTextColor(Color.argb(255, 255, 255, 255));
        gradeButton.setTextColor(Color.argb(255, 255, 255, 255));
        mJSONAdapter.sortByDistance();
    }

    public void sortByTime(View view) {
        distanceButton.setTextColor(Color.argb(255, 255, 255, 255));
        timeButton.setTextColor(Color.argb(255, 67, 193, 228));
        positionButton.setTextColor(Color.argb(255, 255, 255, 255));
        gradeButton.setTextColor(Color.argb(255, 255, 255, 255));
        mJSONAdapter.sortByTime();
    }

    public void sortByGrade(View view) {
        distanceButton.setTextColor(Color.argb(255, 255, 255, 255));
        timeButton.setTextColor(Color.argb(255, 255, 255, 255));
        positionButton.setTextColor(Color.argb(255, 255, 255, 255));
        gradeButton.setTextColor(Color.argb(255, 67, 193, 228));
        mJSONAdapter.sortByGrade();
    }

    public void sortByPosition(View view) {
        distanceButton.setTextColor(Color.argb(255, 255, 255, 255));
        timeButton.setTextColor(Color.argb(255, 255, 255, 255));
        positionButton.setTextColor(Color.argb(255, 67, 193, 228));
        gradeButton.setTextColor(Color.argb(255, 255, 255, 255));
        mJSONAdapter.sortByPosition();
    }

}

